package test4_10.demo03;

import java.io.*;

public class Homework21_12 {

    public static void cutAndMove(File source, File target) throws IOException {
        if (!source.exists()) {
            System.out.println("路径不存在");
            return;
        }

        if (target.isDirectory()) {
            target = new File(target, source.getName());
        }

        if (source.isFile()) {

            target.getParentFile().mkdirs();

            try (InputStream in = new FileInputStream(source);
                 OutputStream out = new FileOutputStream(target)) {
                byte[] buffer = new byte[1024];
                int length;
                while ((length = in.read(buffer)) > 0) {
                    out.write(buffer, 0, length);
                }
            }
            source.delete();
        } else if (source.isDirectory()) {

            target.mkdirs();

            File[] files = source.listFiles();
            if (files != null) {
                for (File file : files) {
                    cutAndMove(file, new File(target, file.getName()));
                }
            }

            source.delete();
        }
    }

    public static void main(String[] args) throws IOException {
        File source = new File("D://test1/a.txt");
        File target = new File("D://test2");
        source.mkdirs();
        target.mkdirs();

        cutAndMove(source, target);
    }
}
